﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Client;

namespace CloudAppCsomDemoWeb.Pages {

  public partial class Default : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
      // configure URL for link backk to host web
      linkHostSite.NavigateUrl = Page.Request["SPHostUrl"];

      // cache url to web app for other pages
      string appWebUrl = Page.Request["SPAppWebUrl"];
      Cache["SPAppWebUrl"] = appWebUrl;

      using (ClientContext clientContext = new ClientContext(appWebUrl)) {
        Web appWeb = clientContext.Web;
        clientContext.Load(appWeb);
        clientContext.ExecuteQuery();
        lblAppWebTitle.Text = appWeb.Title;
      }
    }

    protected void cmdCreateNewList_Click(object sender, EventArgs e) {

      string ListTitle = txtNewListTitle.Text;
      if (string.IsNullOrEmpty(ListTitle)) {
        lblStatus.Text = "ERROR: List title cannot be blank";
        return;
      }

      int ListType = Convert.ToInt32(lstListType.SelectedValue);


      string appWebUrl = Page.Request["SPAppWebUrl"];
      using (ClientContext clientContext = new ClientContext(appWebUrl)) {
        ListCreationInformation newList = new ListCreationInformation();
        newList.Title = ListTitle;
        newList.Url = "Lists/" + ListTitle;
        newList.QuickLaunchOption = QuickLaunchOptions.On;
        newList.TemplateType = ListType;
        clientContext.Web.Lists.Add(newList);
        try {
          clientContext.ExecuteQuery();
          lblStatus.Text = "New " + lstListType.SelectedItem.Text + 
                           " list created with title of " + ListTitle;
        }
        catch (Exception ex) {
          lblStatus.Text = "ERROR: " + ex.Message;
        }
      }

      // add client-side script to asychonously reload lists
      string updateScript = "$('#appweblists').load('/Pages/appWebLists.ashx');";
      ScriptManager.RegisterClientScriptBlock(upNewList, upNewList.GetType(), upNewList.ClientID, updateScript, true);
    }
  }
}